package com.spddr.pmos;

import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import org.apache.cxf.Bus;
import org.apache.cxf.binding.BindingFactoryManager;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.feature.LoggingFeature;
import org.apache.cxf.jaxrs.JAXRSBindingFactory;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.validation.BeanValidationFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

import cn.seqdata.cxf.interceptor.WrappedFaultOutInterceptor;
import cn.seqdata.cxf.interceptor.WrappedOutInterceptor;
import cn.seqdata.cxf.provider.ConstraintViolationExceptionMapper;
import cn.seqdata.cxf.provider.JacksonProvider;
import cn.seqdata.cxf.provider.JodaConverterProvider;

import com.spddr.pmos.oauth2.JaxrsOauthSignImpl;

@Configuration
@ImportResource({ "classpath:META-INF/cxf/cxf.xml" })
public class OauthConfiguration {
	@Autowired
	private ApplicationContext ctx;

	@Bean
	public Server oauthServer() {
		Bus bus = ctx.getBean(Bus.DEFAULT_BUS_ID, Bus.class);

		JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
		sf.setAddress("/oauth");
		sf.setBus(bus);

		//处理joda数据类型如：DateTime/LocalDate/LocalTime/Period...
		sf.setProvider(new JodaConverterProvider());
		//自定义 ObjectMapper，也可以用 JacksonJsonProvider，但需要传入已经定义好的ObjectMapper
		sf.setProvider(new JacksonProvider());//JacksonJsonProvider
		//javax.validations 支持，自动处理注解并抛出 ConstraintViolationException
		sf.setProvider(new ConstraintViolationExceptionMapper());

		//日志记录
		sf.getFeatures().add(new LoggingFeature());
		//输入有效性验证
		sf.getFeatures().add(new BeanValidationFeature());

		//正常输出拦截
		sf.getOutInterceptors().add(new WrappedOutInterceptor());
		//异常输出拦截
		sf.getOutFaultInterceptors().add(new WrappedFaultOutInterceptor());

		Map<Object, Object> extMaps = new HashMap<>();
		extMaps.put(MediaType.APPLICATION_JSON_TYPE.getSubtype(), MediaType.APPLICATION_JSON);
		sf.setExtensionMappings(extMaps);

		sf.setServiceBean(ctx.getBean(JaxrsOauthSignImpl.class));

		JAXRSBindingFactory bf = new JAXRSBindingFactory();
		bf.setBus(bus);

		BindingFactoryManager manager = bus.getExtension(BindingFactoryManager.class);
		manager.registerBindingFactory(JAXRSBindingFactory.JAXRS_BINDING_ID, bf);

		return sf.create();
	}
}
